/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.tenancy.core.context;

import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * MultiTenantInterceptor $
 *
 * @author Hey Law
 * @create 2019年8月21日16:37:27$
 */
    @Aspect
//@Component
public class MultiTenantInterceptor {

//    /**
//     * 定义拦截规则：拦截com.xjj.web.controller包下面的所有类中，有@RequestMapping注解的方法。
//     */
//    @Pointcut("execution(* io.iec.edp.caf.tenancy.core.service..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
//    public void controllerMethodPointcut(){}

    //指定了io.iec.edp.caf.tenancy.core.service这样的包及其子包下的所有方法才会被拦截
    @Pointcut("execution(* io.iec.edp.caf.tenancy.core.service..*(..))")
    public void tenantServicePointcut(){}

    /**
     * 拦截器具体实现
     * @param pjp
     * @return JsonResult（被拦截方法的执行结果，或需要登录的错误提示。）
     */
    @Around("tenantServicePointcut()") //指定拦截器规则
    public Object interceptor(ProceedingJoinPoint pjp){

        Object result = null;
        //完成Master数据库设置
        try
        {
            MultiTenantContextInfo multiTenantContextInfo = new MultiTenantContextInfo();
            multiTenantContextInfo.setMasterDb(true);

            MultiTenantContextHolder.set(multiTenantContextInfo);
            // 一切正常的情况下，继续执行被拦截的方法
            result = pjp.proceed();
        }
        catch (Throwable throwable){
            throw new RuntimeException(throwable);
        }finally {
            MultiTenantContextHolder.set(null);
        }

        return result;
    }
}
